package org.icnmasjid.member.webapp.action;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.icnmasjid.member.Constants;
import org.icnmasjid.member.util.CommonUtil;
import org.icnmasjid.member.util.DesEncrypter;
import org.icnmasjid.member.webapp.action.BaseFormController;
import org.icnmasjid.member.model.Person;
import org.icnmasjid.member.model.PersonPayment;
import org.icnmasjid.member.model.PersonSubOrgRole;
import org.icnmasjid.member.model.Role;
import org.icnmasjid.member.model.SubOrg;
import org.icnmasjid.member.service.PersonManager;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import com.sun.mail.iap.Response;

public class EmailPersonRestrictedController extends BaseFormController {

	private PersonManager personManager;

    public void setPersonManager(PersonManager personManager) {
        this.personManager = personManager;
    }

    public EmailPersonRestrictedController() {
    	setCommandClass(Person.class);
    	setCommandName("person");
	}

    public ModelAndView onSubmit(HttpServletRequest request,
                                 HttpServletResponse response, Object command,
                                 BindException errors)
    throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("entering 'onSubmit' method...");
        }
        Locale locale = request.getLocale();
        boolean success = false;
        Person p = null;

        if ( "showPerson".equals(request.getParameter("action")) ) {
			String passKey = request.getParameter("passKey");
			if ( StringUtils.isNotBlank(passKey) ) {
				String personId = new DesEncrypter(Constants.CRYPTO_KEY).decrypt(URLDecoder.decode(passKey,"UTF-8"));
				if ( NumberUtils.isNumber(personId) ) {
					p = personManager.getPerson(personId);
					saveMessage(request, "person Id: " + personId + " email: " + p.getEmail() + " email2: " + p.getEmail2());
					success = true;
				}
			}
        }

	    String email = request.getParameter("email");
	    if ( StringUtils.isNotBlank(email) ) {
        	p = personManager.getPersonByEmail(email);
        }

        if ( "showKey".equals(request.getParameter("action")) && p != null ) {
            saveMessage(
            		request,
            			"key is: "
            		+	new DesEncrypter(Constants.PASS_PHRASE).encrypt(""+p.getPersonId())
            		+	" Encoded: "
            		+	URLEncoder.encode(
	        				new DesEncrypter(Constants.PASS_PHRASE).encrypt( "" + p.getPersonId() ),
	        				"UTF-8"
            			)
            );
            success = true;
        }

        if ( "sendEmail".equals(request.getParameter("action")) && p != null ) {
            sendEmail(p, email, locale);
            p.setEmailSent(new Timestamp(System.currentTimeMillis()));
            personManager.savePerson(p);
            saveMessage(request, getText("email.sent", locale));
            success = true;
        }

        if ( !success ) {
        	saveMessage(request, getText("email.not.found", locale));
        }

        return new ModelAndView("redirect:emailRestricted.html");
    }

	private void sendEmail(Person p, String email, Locale locale) throws Exception{
		CommonUtil.send(
				email,
				getText("email.subject", locale),
				getText(
					"email.content.personal",
					new Object[] {
						URLEncoder.encode(
							new DesEncrypter(Constants.PASS_PHRASE)
								.encrypt(
									""+p.getPersonId()
								)
							,"UTF-8"
						),
						p.getFirstName()+" " + p.getLastName()
					}
					, locale
				)
			);
	}
}